package com.tanfuqi.sicent.client.filter

import com.tanfuqi.sicent.client.mapper.OnlineMapper
import com.tanfuqi.sicent.client.mapper.ShiftMapper
import com.tanfuqi.sicent.protocol.message.Message
import org.apache.mina.core.filterchain.IoFilter
import org.apache.mina.core.filterchain.IoFilterAdapter
import org.apache.mina.core.session.IoSession
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import reactor.core.publisher.Mono
import reactor.core.publisher.toMono
import java.util.*

@Component
class DatabaseFilter : IoFilterAdapter() {

    @Autowired
    val onlineMapper: OnlineMapper? = null
    @Autowired
    val shiftMapper: ShiftMapper? = null

    override fun messageReceived(nextFilter: IoFilter.NextFilter?, session: IoSession?, message: Any?) {
        Mono.justOrEmpty(message).cast(Message::class.java).flatMap {
            it.toMono().doOnSuccess { message ->
                when (message.type) {
                    0x9001 -> {
                        Mono.justOrEmpty(it.body).cast(Map::class.java).map { it["computer"] as String }.map {
                            onlineMapper?.getOnlineCardIdByComputerName("%$it")
                        }.doOnSuccess {
                            session?.write(Message(0x90009001L.toInt(), id = message.id, body = it))
                        }.subscribe()
                    }
                    0x9002 -> {
                        Mono.justOrEmpty(it.body).cast(Map::class.java).flatMap { params ->
                            Mono.justOrEmpty<IoSession>(session).doOnSuccess {
                                it.write(Message(0x90009002L.toInt(), id = message.id, body = shiftMapper?.history(Date(params["from"] as Long), Date(params["to"] as Long))))
                            }
                        }.subscribe()

                    }

                    else -> super.messageReceived(nextFilter, session, message)
                }
            }
        }.subscribe()
//        super.messageReceived(nextFilter, session, message)
    }
}